package com.cskaoyan.config.shiro.realm;

import com.cskaoyan.bean.po.*;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketPermissionMapper;
import com.cskaoyan.mapper.MarketRoleMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description: shiro组件中realm配置所需实现类,用于提供认证和授权信息
 * @Author: Pinocao
 * @CreateTime: 2022-11-21  17:28
 * @Version: 1.0
 */
@Component
public class CustomWebRealm extends AuthorizingRealm {
    @Autowired
    MarketAdminMapper marketAdminMapper;
    @Autowired
    MarketRoleMapper marketRoleMapper;
    @Autowired
    MarketPermissionMapper marketPermissionMapper;

    // 完成登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取username，在数据查询有无该管理员用户
        String username = (String) authenticationToken.getPrincipal();
        MarketAdminExample marketAdminExample = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = marketAdminExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        criteria.andDeletedEqualTo(false);
        List<MarketAdmin> list = marketAdminMapper.selectByExample(marketAdminExample);
        if (list.size()==1){
            // 此处说明有该用户
            MarketAdmin marketAdmin = list.get(0);
            String password = marketAdmin.getPassword();
            // 第一个参数principal放入认证后的用户信息，第二个参数Credentials是正确的密码，会和token中的密码比对
            return new SimpleAuthenticationInfo(marketAdmin,password,getName());
        }

        return null;
    }

    // 完成授权权限匹配
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取principal，43行放入的MarketAdmin
        MarketAdmin primaryPrincipal = (MarketAdmin) principalCollection.getPrimaryPrincipal();
        // 查询对应权限
        Integer[] roleIds = primaryPrincipal.getRoleIds();
        List<String> permissionList = marketPermissionMapper.selectByRoleIds(roleIds);
        // 将管理员用户对应的权限集合放入SimpleAuthorizationInfo
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permissionList);
        return simpleAuthorizationInfo;
    }
}